#!/usr/bin/env python
# -*- coding: utf-8 -*-

from WSModule import WSModule
from WSThread import WSThread
from WSJob import WSJob
from WSResult import WSResult
from WSOption import WSOption
import queue
import http.client
import os
from collections import OrderedDict

class Ping(WSModule):
	log_path = os.getcwd() + '/results/Ping-result'
	description = "Host Pinger"
	options = OrderedDict([
		("threads",WSOption("threads", "count thread", 5, False, ['-t', '--threads'])),
		("file",WSOption("file", "file with host", "hosts.txt", True, ['-f', '--file']))])
	def run(self):
		self.job = PingJob(self.options["file"].value)
		self.result = PingResult()
		workers = []
		for i in range(int(self.options["threads"].value)):
			workers.append(PingThread(self.job, self.result))
		self.kernel.createThreads(workers)
		
	def help(self):
		return "Ping module ver 0"
	def finished(self):
		return self.kernel.finished()
	def getResult(self):
		return self.result.as_string()

class PingThread(WSThread):
	def run(self):
		while self.running:
			try:
				host = self.job.get(False)
				try:
					conn = http.client.HTTPConnection(host,timeout = 5)
					conn.request("GET", "/")
					conn.close()
					self.result.put(host)
				except:
					pass
			except queue.Empty:
				self.running = False

class PingJob(WSJob):
	def __init__(self, filename):
		WSJob.__init__(self)
		f = open(filename)
		for host in f.readlines():
			self.put(host.strip())
		f.close()

class PingResult(WSResult):pass
